package com.wchat.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wchat.configurer.JwtConfig;
import com.wchat.service.AuthUtilService;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Calendar;

/**
 * Created by 瑞 on 01/7/2018.
 */
@Service
public class AuthUtilServiceImpl implements AuthUtilService {


    @Autowired private JwtConfig jwtConfig;

    @Override
    public String createJwt(AuthUtilService.AuthInfo authInfo) {
        JSONObject obj = JSON.parseObject(JSON.toJSONString(authInfo));
        return Jwts.builder()
                   .setClaims(obj)
                   .signWith(SignatureAlgorithm.HS512, getKey())
                   .compact();
    }

    @Override
    public AuthInfo decryptFromJwt(String token) {
        AuthInfo result = null;
        try {
            result = JSON.parseObject(JSON.toJSONString(Jwts.parser()
                                                            .setSigningKey(getKey())
                                                            .parseClaimsJws(token)
                                                            .getBody()), AuthInfo.class);
        } catch (ExpiredJwtException ex1) {
            //TODO need to process the expiredException
        } catch (SignatureException ex) {
        }
        return result;
    }


    //通过把用户信息作为object来创建jwt 其中key也可以直接使用 Macprovider.generatekey(); 直接生成
    @Override
    public String createJwt(AuthInfo authInfo, Integer expireTimeInMinutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, expireTimeInMinutes);
        JSONObject obj = JSON.parseObject(JSON.toJSONString(authInfo));
        return Jwts.builder()
                   .setClaims(obj)
                   .setExpiration(calendar.getTime())
                   .signWith(SignatureAlgorithm.HS512, getKey())
                   .compact();
    }


    @Override
    public AuthInfo createAuthInfo(Integer userId,AuthUtilService.UserType userType) {
        AuthInfo authInfo = new AuthInfo();
        authInfo.userId = userId;
        authInfo.userType = userType.USER;
        authInfo.nonce = System.currentTimeMillis();
        return authInfo;
    }


    private Key getKey() {
        return new SecretKeySpec(jwtConfig.getJwtKey().getBytes(), SignatureAlgorithm.HS512.getJcaName());

    }


}
